#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
最终测试脚本 - 验证所有功能修复
"""

import json
import sys
from pathlib import Path

def test_database_migration():
    """测试数据库迁移"""
    print("🔄 测试数据库迁移...")
    
    try:
        from database import template_dao
        
        # 测试新字段
        template_id = template_dao.create_template(
            name="测试底板(带图片路径)",
            width=800,
            height=600,
            description="测试新字段",
            image_path="test.tif",
            original_filename="original_test.tif"
        )
        
        template = template_dao.get_template_by_id(template_id)
        
        assert template['image_path'] == "test.tif", "image_path字段测试失败"
        assert template['original_filename'] == "original_test.tif", "original_filename字段测试失败"
        
        print("✅ 数据库迁移测试通过")
        return True
        
    except Exception as e:
        print(f"❌ 数据库迁移测试失败: {e}")
        return False

def test_cors_proxy():
    """测试CORS代理功能"""
    print("\n🌐 测试CORS代理功能...")
    
    try:
        from app import app
        
        with app.test_client() as client:
            # 测试代理端点
            test_url = "https://httpbin.org/image/png"
            response = client.get(f'/proxy_image?url={test_url}')
            
            print(f"✅ 代理响应状态: {response.status_code}")
            print(f"✅ 响应类型: {response.content_type}")
            
            # 检查CORS头
            assert 'Access-Control-Allow-Origin' in response.headers
            print("✅ CORS头设置正确")
            
        return True
        
    except Exception as e:
        print(f"❌ CORS代理测试失败: {e}")
        return False

def test_json_processing_with_proxy():
    """测试使用代理的JSON处理"""
    print("\n📊 测试JSON处理（使用代理）...")
    
    try:
        from image_processor import ImageProcessor
        from database import template_dao, region_dao
        
        # 创建测试底板和区域
        template_id = template_dao.create_template("代理测试底板", 1350, 1350, "用于测试代理功能")
        region_id = region_dao.create_region(template_id, "测试区域", 100, 100, 300, 300)
        
        # 获取底板和区域
        template = template_dao.get_template_by_id(template_id)
        regions = region_dao.get_regions_by_template(template_id)
        
        # 准备测试数据
        customization_data = {
            'regions': {
                '0': {
                    'elements': [{
                        'image_url': 'https://httpbin.org/image/png',
                        'user_placement_data': {
                            'position': {'x': 100, 'y': 100},
                            'scale': {'scale_x': 0.5, 'scale_y': 0.5},
                            'angle_of_rotation': 0
                        }
                    }]
                }
            }
        }
        
        # 测试图片生成
        processor = ImageProcessor()
        result_path = processor.create_customized_image(
            template=dict(template),
            regions=[dict(region) for region in regions],
            customization_data=customization_data
        )
        
        print(f"✅ 图片生成成功: {result_path}")
        return True
        
    except Exception as e:
        print(f"❌ JSON处理测试失败: {e}")
        return False

def test_file_structure():
    """测试文件结构"""
    print("\n📁 测试文件结构...")
    
    required_files = [
        'app.py', 'config.py', 'database.py', 'image_processor.py',
        'requirements.txt', 'run.py', 'migrate_db.py',
        'templates/base.html', 'templates/index.html', 'templates/templates.html',
        'static/css/style.css', 'static/css/enterprise.css',
        'static/js/common.js', 'static/js/templates.js'
    ]
    
    missing_files = []
    for file_path in required_files:
        if not Path(file_path).exists():
            missing_files.append(file_path)
    
    if missing_files:
        print(f"❌ 缺少文件: {missing_files}")
        return False
    
    print("✅ 所有必需文件都存在")
    return True

def main():
    """主测试函数"""
    print("🎨 图片定制工具 - 最终功能测试")
    print("="*60)
    
    tests = [
        test_file_structure,
        test_database_migration,
        test_cors_proxy,
        test_json_processing_with_proxy
    ]
    
    passed = 0
    total = len(tests)
    
    for test in tests:
        try:
            if test():
                passed += 1
        except Exception as e:
            print(f"❌ 测试异常: {e}")
    
    print("\n" + "="*60)
    print(f"📊 测试结果: {passed}/{total} 通过")
    
    if passed == total:
        print("🎉 所有测试通过！")
        print("\n✨ 主要修复:")
        print("   🎨 企业化侧边栏布局")
        print("   📤 TIF文件上传功能") 
        print("   🖼️ CORS图片代理")
        print("   🐛 JavaScript错误修复")
        print("   💼 若依风格界面")
        print("\n🚀 启动应用:")
        print("   python run.py")
        print("\n🌐 访问地址:")
        print("   http://localhost:5000")
    else:
        print("⚠️  部分测试失败，请检查错误信息。")
    
    return passed == total

if __name__ == '__main__':
    success = main()
    sys.exit(0 if success else 1)
